

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cheney">
  <meta name="keywords" content="Coding">
  
    <meta name="description" content="图象是一种非常常见的信息载体，但是在图像的获取、传输、存储过程中可能由于各种原因使得图像受到噪声的影响。如何去除噪声的影响，恢复图像原本的信息是计算机视觉中的重要研究问题。常见的图像恢复算法有基于空间域的中值滤波、基于小波域的小波去噪、基于偏微分方程的非线性扩散滤波等。本次实验对图像添加噪声，并对添加噪声的图像进行基于线性回归模型的去噪。">
<meta property="og:type" content="article">
<meta property="og:title" content="图像恢复(加噪与去噪)">
<meta property="og:url" content="https://cheney822.gitee.io/2021/10/03/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD__%E5%9B%BE%E5%83%8F%E6%81%A2%E5%A4%8D(%E5%8A%A0%E5%99%AA%E4%B8%8E%E5%8E%BB%E5%99%AA)/index.html">
<meta property="og:site_name" content="Cheney blog">
<meta property="og:description" content="图象是一种非常常见的信息载体，但是在图像的获取、传输、存储过程中可能由于各种原因使得图像受到噪声的影响。如何去除噪声的影响，恢复图像原本的信息是计算机视觉中的重要研究问题。常见的图像恢复算法有基于空间域的中值滤波、基于小波域的小波去噪、基于偏微分方程的非线性扩散滤波等。本次实验对图像添加噪声，并对添加噪声的图像进行基于线性回归模型的去噪。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/fee15e6f469444ccb2924f5760d68884-20220405210303331.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/b4d67d907ccc40b5aac8181acb150e60-20220405210303372.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/1746eec8231a43c0a101ea9814a2fd05-20220405210303416.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/16f32cde5ef0441d8689e23b83eb9d46-20220405210303491.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/83ff5a02ffae4f97b49494b61ef2c08d-20220405210303535.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/0c759ed1a1bb42679c7234dfe6864688-20220405210303610.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/4ca2c85f8c6c4b5fbab770601a31b441-20220405210303664.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/fc24a10fdbeb44e1bf48391a0ab997f1-20220405210303750.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/e134fa3bd95949eeadfcd016db009a3f-20220405210303799.png">
<meta property="article:published_time" content="2021-10-03T05:14:00.000Z">
<meta property="article:modified_time" content="2022-04-05T13:14:31.523Z">
<meta property="article:author" content="Cheney">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="OpenCv">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://imgbed.cheney.cc/picgo/fee15e6f469444ccb2924f5760d68884-20220405210303331.png">
  
  
  <title>图像恢复(加噪与去噪) - Cheney blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"cheney822.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":1},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Cheney Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://imgbed.cheney.cc/Blog_config/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="图像恢复(加噪与去噪)">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-10-03 13:14" pubdate>
        2021年10月3日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      6.6k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      34 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">图像恢复(加噪与去噪)</h1>
            
            <div class="markdown-body">
              <p><kbd> ==人工智能导论实验导航== </kbd></p>
<p>==实验一：斑马问题== <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_46291251/article/details/122246347">https://blog.csdn.net/weixin_46291251/article/details/122246347</a></p>
<p>==实验二：图像恢复== <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_46291251/article/details/122561220">https://blog.csdn.net/weixin_46291251/article/details/122561220</a></p>
<p>==实验三：花卉识别== <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_46291251/article/details/122561505">https://blog.csdn.net/weixin_46291251/article/details/122561505</a></p>
<p>==实验四：手写体生成== <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_46291251/article/details/122576478">https://blog.csdn.net/weixin_46291251/article/details/122576478</a></p>
<p>==实验源码：== xxx</p>
<h1 id="2-1实验介绍"><a href="#2-1实验介绍" class="headerlink" title="2.1实验介绍"></a>2.1实验介绍</h1><h2 id="2-1-1实验背景"><a href="#2-1-1实验背景" class="headerlink" title="2.1.1实验背景"></a>2.1.1实验背景</h2><p><strong>机器学习：</strong><br>机器学习是一类算法的总称，这些算法企图从大量历史数据中挖掘出其中隐含的规律，并用于预测或者分类，更具体的说，机器学习可以看作是寻找一个函数，输入是样本数据，输出是期望的结果，只是这个函数过于复杂，以至于不太方便形式化表达。需要注意的是，机器学习的目标是使学到的函数很好地适用于“新样本”，而不仅仅是在训练样本上表现很好。学到的函数适用于新样本的能力，称为泛化（Generalization）能力。</p>
<p>机器学习作为人工智能核心技术，本章主要围绕机器学习涉及的决策树、主成分分析和集成算法而设计的实验。本章实验难度分均为初级。</p>
<p><strong>图像恢复：</strong><br>图象是一种非常常见的信息载体，但是在图像的获取、传输、存储过程中可能由于各种原因使得图像受到噪声的影响。如何去除噪声的影响，恢复图像原本的信息是计算机视觉中的重要研究问题。<br>常见的图像恢复算法有基于空间域的中值滤波、基于小波域的小波去噪、基于偏微分方程的非线性扩散滤波等。本次实验对图像添加噪声，并对添加噪声的图像进行基于线性回归模型的去噪。</p>
<h2 id="2-1-2实验目的"><a href="#2-1-2实验目的" class="headerlink" title="2.1.2实验目的"></a>2.1.2实验目的</h2><p>本章实验的主要目的是掌握机器学习相关基础知识点，了解机器学习相关基础知识，经典降维方法、决策树算法和集成算法。熟悉机器学习的一般流程，具备使用python语言和机器学习算法解决实际问题的能力。 </p>
<p>学习Python的Opencv库进行图像相关处理<br>学习Python的Numpy库进行相关数值计算<br>学习线性回归模型的应用</p>
<h2 id="2-1-3实验简介"><a href="#2-1-3实验简介" class="headerlink" title="2.1.3实验简介"></a>2.1.3实验简介</h2><p><strong>A. 生成受损图像。</strong><br>受损图像（X）是由原始图像（I∈RH∗W∗CI∈RH∗W∗C）添加了不同噪声遮罩（noise masks）（M∈RH∗W∗CM∈RH∗W∗C）得到的（X=I⨀MX=I⨀M），其中⨀⨀是逐元素相乘。<br>噪声遮罩仅包含 {0,1} 值。对原图的噪声遮罩的可以每行分别用 0.8/0.4/0.6 的噪声比率产生的，即噪声遮罩每个通道每行 80%/40%/60% 的像素值为 0，其他为 1。</p>
<p><strong>B. 使用你最擅长的算法模型，进行图像恢复。</strong></p>
<p><strong>C. 评估误差为所有恢复图像（R）与原始图像（I）的 2-范数之和，此误差越小越好。</strong><br>error=∑3i=1norm(Ri(:)−Ii(:),2)error=∑i=13norm(Ri(:)−Ii(:),2)，其中(:)是向量化操作，其他评估方式包括 Cosine 相似度以及 SSIM 相似度。</p>
<h1 id="2-2概要设计"><a href="#2-2概要设计" class="headerlink" title="2.2概要设计"></a>2.2概要设计</h1><p><strong>程序分为以下几步：</strong><br>首先进行图片的读取，这里要注意matplotlib和opencv读取图片格式的不同，需要进行转换。然后将数据线性归一化，然后在原图上生成噪声比率为0.6的噪声，得到含噪的图片，这里添加的噪声类型为椒盐噪声。然后用中值滤波器对图像滤波以实现图像恢复。</p>
<p><strong>实验的关键是加噪和去噪</strong><br>加噪用的是<strong>椒盐噪声</strong>，椒盐噪声(salt-and-pepper noise)即一种是盐噪声（salt noise），另一种是胡椒噪声（pepper noise）。盐=白色(0)，椒=黑色(255)。前者是高灰度噪声，后者属于低灰度噪声。这里两种噪声同时出现，呈现在图像上就是黑白杂点<br>去噪用的是<strong>中值滤波</strong>法：使用滤波器窗口包含区域的像素值的中值来得到窗口中心的像素值。是一种非线性平滑滤波器。在去噪同时,较好的保持边缘轮廓细节，适合处理椒盐噪声，但对高斯噪声效果不好。</p>
<h1 id="2-3详细设计"><a href="#2-3详细设计" class="headerlink" title="2.3详细设计"></a>2.3详细设计</h1><h2 id="2-3-1-导入工具包"><a href="#2-3-1-导入工具包" class="headerlink" title="2.3.1 导入工具包"></a>2.3.1 导入工具包</h2><p>matplotlib数据库下的pyplot模块是一个常用于图像展示的模块；<br>Numpy数据库用于相关的数值计算；<br><strong>cv2</strong>，即opencv库，计算机视觉库，常用于图像的处理；<br>从sklearn.linear_model模块下导入线性回归(LinearRegression),岭回归(Ridge),Lasso回归。<br><strong>岭回归</strong>(Ridge)：在线性回归的基础上加了L2正则化项(L2范数)，增加线性回归的泛化性能，它和一般线性回归的区别是在损失函数上增加了一个L2正则化的项，和一个调节线性回归项和正则化项权重的系数α。损失函数表达式如下：<br>J(θ)=(1/2)(Xθ−Y)T(Xθ−Y) + (1/2)α||θ||2<br>其中α为常数系数，需要进行调优。 ||θ||2 为L2范数。Ridge回归的解法和一般线性回归大同小异。<br><strong>Lasso回归</strong>:有时也叫做线性回归的L1正则化，和Ridge回归的主要区别就是在正则化项，Ridge回归用的是L2正则化，而Lasso回归用的是L1正则化。Lasso回归的损失函数表达式如下：<br>J(θ)=(1/2)(Xθ−Y)T(Xθ−Y)+α||θ||1<br>其中α为常数系数，需要进行调优。 ||θ||1 为L1范数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></div></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> matplotlib <span class="hljs-keyword">import</span> pyplot <span class="hljs-keyword">as</span> plt                                  <span class="hljs-comment"># 展示图片</span><br><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np                                               <span class="hljs-comment"># 数值处理</span><br><span class="hljs-keyword">import</span> cv2                                                       <span class="hljs-comment"># opencv库</span><br><span class="hljs-keyword">from</span> sklearn.linear_model <span class="hljs-keyword">import</span> LinearRegression, Ridge, Lasso          <span class="hljs-comment"># 回归分析</span><br></code></pre></td></tr></table></figure>

<h2 id="2-3-2-读取图片："><a href="#2-3-2-读取图片：" class="headerlink" title="2.3.2 读取图片："></a>2.3.2 读取图片：</h2><p>读取图片我们采用 cv2.imread(filename[, flags]) 函数：</p>
<blockquote>
<p>filename：文件路径<br>flags：指定加载图像颜色类型的标志<br>cv2.IMREAD_COLOR：读入一副彩色图像。图像的透明度会被忽略，这是默认参数，此时 flags=1。<br>cv2.IMREAD_GRAYSCALE：以灰度模式读入图像，此时 flags=0。<br>cv2.IMREAD_UNCHANGED：读入一幅图像，并且包括图像的 alpha 通道，此时 flags=-1。</p>
</blockquote>
<p>彩色图像使用 OpenCV 加载时是 BGR 模式，但是 Matplotlib 是 RGB 模式。所以彩色图像如果已经被 OpenCV 读取，那它将不会被 Matplotlib 正确显示。因此我们将 BGR模式转换为 RGB 模式即可。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">read_image</span>(<span class="hljs-params">img_path</span>):<br><span class="hljs-comment"># 读取图片</span><br>    img = cv2.imread(img_path) <br>    <span class="hljs-comment"># 如果图片是三通道，采用 matplotlib 展示图像时需要先转换通道</span><br>    <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(img.shape) == <span class="hljs-number">3</span>:<br>        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)   <br><span class="hljs-keyword">return</span> img<br><br>img_path = <span class="hljs-string">&#x27;A.png&#x27;</span><span class="hljs-comment"># 加载图片的路径和名称</span><br>img = read_image(img_path)  <span class="hljs-comment"># 读取图片</span><br><span class="hljs-built_in">print</span>(<span class="hljs-built_in">type</span>(img))<span class="hljs-comment"># 读取图片后图片的类型</span><br>plt.imshow(img)  <span class="hljs-comment"># 展示图片</span><br>plt.axis(<span class="hljs-string">&#x27;off&#x27;</span>) <span class="hljs-comment"># 关闭坐标</span><br></code></pre></td></tr></table></figure>

<h2 id="2-3-3-保存图片"><a href="#2-3-3-保存图片" class="headerlink" title="2.3.3 保存图片"></a>2.3.3 保存图片</h2><p>OpenCV 保存一个图片使用函数 cv2.imwrite(filename, img[, params])：<br>filename：保存文件路径及文件名，文件名要加格式<br>img：需要保存的图片</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">save_image</span>(<span class="hljs-params">filename, image</span>):<br>    <span class="hljs-comment"># np.copy() 函数创建一个副本。</span><br>    <span class="hljs-comment"># 对副本数据进行修改，不会影响到原始数据，它们物理内存不在同一位置。</span><br>    img = np.copy(image)<br>    img = img.squeeze()<span class="hljs-comment"># 从给定数组的形状中删除一维的条目</span><br>    <br>    <span class="hljs-keyword">if</span> img.dtype == np.double:    <span class="hljs-comment"># 将图片数据存储类型改为 np.uint8</span><br>        <span class="hljs-comment"># 若img数据存储类型是 np.double ,则转化为 np.uint8 形式</span><br>        img = img * np.iinfo(np.uint8).<span class="hljs-built_in">max</span><br>        img = img.astype(np.uint8)        <span class="hljs-comment"># 转换图片数组数据类型</span><br>        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)<span class="hljs-comment"># 将 RGB 方式转换为 BGR 方式</span><br>     cv2.imwrite(filename, img)<span class="hljs-comment"># 生成图片</span><br></code></pre></td></tr></table></figure>



<h2 id="2-3-4-归一化"><a href="#2-3-4-归一化" class="headerlink" title="2.3.4 归一化"></a>2.3.4 归一化</h2><p>机器学习过程中，数据归一化非常重要，归一化的目标主要有：<br>把数变为（0,1）或者（-1,1）之间的小数<br>把有量纲表达式变为无量纲表达式<br>常见的归一化方法有:<br>线性比例变换法  xi=xi / max(x)<br>min-max标准化  xi=[xi−min(x)] /[ max(x)−min(x)]<br>z-score 标准化  xi=[xi−mean(x) ]/ σ </p>
<p>下面我们来实现线性比例变化法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">normalization</span>(<span class="hljs-params">image</span>):<br>       info = np.iinfo(image.dtype)  <span class="hljs-comment"># 获取图片数据类型对象的最大值和最小值</span><br><span class="hljs-keyword">return</span> image.astype(np.double) / info.<span class="hljs-built_in">max</span>    <span class="hljs-comment"># 图像数组数据放缩在 0-1 之间</span><br></code></pre></td></tr></table></figure>


<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python">img_path = <span class="hljs-string">&#x27;A.png&#x27;</span><span class="hljs-comment"># 图片的路径和名称</span><br>img = read_image(img_path)<span class="hljs-comment"># 读取图片</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;没有归一化的数据：\n&quot;</span>, img[<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, :])<span class="hljs-comment"># 展示部分没有归一化的数据:</span><br>img = normalization(img)<span class="hljs-comment"># 图片数据归一化</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;归一化后的数据：\n&quot;</span>, img[<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, :])<span class="hljs-comment"># 展示部分 归一化后的数据</span><br></code></pre></td></tr></table></figure>


<h2 id="2-3-5-图片加噪"><a href="#2-3-5-图片加噪" class="headerlink" title="2.3.5 图片加噪"></a>2.3.5 图片加噪</h2><p>生成受损图像的实验要求：</p>
<p>受损图像（X）是由原始图像（ I∈RH∗W∗C ）添加了不同噪声遮罩（noise masks）（ M∈RH∗W∗C ）得到的（ X=I⨀M ），其中  ⨀  是逐元素相乘。</p>
<p>噪声遮罩仅包含 {0,1} 值。对原图的噪声遮罩的可以每行分别用 0.8/0.4/0.6 的噪声比率产生的，即噪声遮罩每个通道每行 80%/40%/60% 的像素值为0，其他为1。</p>
<p>椒盐噪声(salt-and-pepper noise)是指两种噪声，一种是盐噪声（salt noise），另一种是胡椒噪声（pepper noise）。盐=白色(0)，椒=黑色(255)。前者是高灰度噪声，后者属于低灰度噪声。一般两种噪声同时出现，呈现在图像上就是黑白杂点<br><img src="https://imgbed.cheney.cc/picgo/fee15e6f469444ccb2924f5760d68884-20220405210303331.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>以下使用的是一个阈值（prob、thres）进行的噪声分布：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">noise_mask_image</span>(<span class="hljs-params">img, noise_ratio</span>):<br>    <span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">    根据题目要求生成受损图片</span><br><span class="hljs-string">    :param img: 图像矩阵，一般为 np.ndarray</span><br><span class="hljs-string">    :param noise_ratio: 噪声比率，可能值是0.4/0.6/0.8</span><br><span class="hljs-string">    :return: noise_img 受损图片, 图像矩阵值 0-1 之间，数据类型为 np.array, </span><br><span class="hljs-string">             数据类型对象 (dtype): np.double, 图像形状:(height,width,channel),通道(channel) 顺序为RGB</span><br><span class="hljs-string">    &quot;&quot;&quot;</span><br>    <span class="hljs-comment"># 受损图片初始化</span><br>      noise_img = np.zeros(img.shape, np.double)<br>    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(img.shape[<span class="hljs-number">0</span>]):<br>        <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(img.shape[<span class="hljs-number">1</span>]):<br>            <span class="hljs-keyword">if</span> random.random() &lt; noise_ratio:  <span class="hljs-comment"># 如果生成的随机数小于噪声比例则将该像素点添加黑点</span><br>                noise_img[i][j] = <span class="hljs-number">0</span>  <span class="hljs-comment"># 1 / 0</span><br>            <span class="hljs-keyword">elif</span> random.random() &gt; <span class="hljs-number">1</span>-noise_ratio:<br>                noise_img[i][j] = <span class="hljs-number">1</span>  <span class="hljs-comment"># 1 / 0</span><br>            <span class="hljs-keyword">else</span>:<br>                noise_img[i][j] = img[i][j]<br><br>    <span class="hljs-keyword">return</span> noise_img<br></code></pre></td></tr></table></figure>

<h2 id="2-3-6-误差评估"><a href="#2-3-6-误差评估" class="headerlink" title="2.3.6 误差评估"></a>2.3.6 误差评估</h2><p>评估误差为所有恢复图像（R）与原始图像（I）的2-范数之和，此误差越小越好。 error=∑3i=1norm(Ri(:)−Ii(:),2) ，其中(:)是向量化操作</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">compute_error</span>(<span class="hljs-params">res_img, img</span>):<br>    error = <span class="hljs-number">0.0</span>    <span class="hljs-comment"># 初始化</span><br>    res_img = np.array(res_img)    <span class="hljs-comment"># 将图像矩阵转换成为np.narray</span><br>    img = np.array(img)<br>    <span class="hljs-keyword">if</span> res_img.shape != img.shape:    <span class="hljs-comment"># 如果2个图像的形状不一致，则打印出错误结果，返回值为 None</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;shape error res_img.shape and img.shape %s != %s&quot;</span> % (res_img.shape, img.shape))<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span><br>    error = np.sqrt(np.<span class="hljs-built_in">sum</span>(np.power(res_img - img, <span class="hljs-number">2</span>)))    <span class="hljs-comment"># 计算图像矩阵之间的评估误差</span><br><span class="hljs-keyword">return</span> <span class="hljs-built_in">round</span>(error,<span class="hljs-number">3</span>)<br></code></pre></td></tr></table></figure>

<p>#计算平面二维向量的 2-范数值 </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python">img0 = [<span class="hljs-number">1</span>, <span class="hljs-number">0</span>]<br>img1 = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>]<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;平面向量的评估误差：&quot;</span>, compute_error(img0, img1))<br></code></pre></td></tr></table></figure>

<h2 id="2-3-7-图像恢复"><a href="#2-3-7-图像恢复" class="headerlink" title="2.3.7 图像恢复"></a>2.3.7 图像恢复</h2><p><strong>中值滤波器</strong>，使用滤波器窗口包含区域的像素值的中值来得到窗口中心的像素值。是一种非线性平滑滤波器。在去噪同时,较好的保持边缘轮廓细节，适合处理椒盐噪声，但对高斯噪声效果不好。<br><img src="https://imgbed.cheney.cc/picgo/b4d67d907ccc40b5aac8181acb150e60-20220405210303372.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>中值滤波原理:</strong><br>选一个含有奇数点的窗口W，将这个窗口在图像上扫描，把窗口中所含的像素点按灰度级的升或降序排列，取位于中间的灰度值来代替该点的灰度值。 例如选择滤波的窗口如下图，是一个一维的窗口，待处理像素的灰度取这个模板中灰度的中值.<br>换成图像模板来理解就是将临近像素按照大小排列，取排序像素中位于中间位置的值作为中值滤波的像素值</p>
<p><strong>中值滤波流程图：</strong><br><img src="https://imgbed.cheney.cc/picgo/1746eec8231a43c0a101ea9814a2fd05-20220405210303416.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">restore_image</span>(<span class="hljs-params">noise_img, size=<span class="hljs-number">4</span></span>):<br>    img = noise_img<br>    size = <span class="hljs-number">5</span>  <span class="hljs-comment"># 核尺寸</span><br>    num = <span class="hljs-built_in">int</span>((size - <span class="hljs-number">1</span>) / <span class="hljs-number">2</span>)  <span class="hljs-comment"># 输入图像需要填充的尺寸</span><br>    img = cv2.copyMakeBorder(img, num, num, num, num, cv2.BORDER_REPLICATE)<br>    h, w = img.shape[<span class="hljs-number">0</span>:<span class="hljs-number">2</span>]  <span class="hljs-comment"># 获取输入图像的长宽和高</span><br>    h-=<span class="hljs-number">4</span>;w-=<span class="hljs-number">4</span><br>    img1 = np.zeros((h, w, <span class="hljs-number">3</span>), dtype=<span class="hljs-string">&quot;uint8&quot;</span>)  <span class="hljs-comment"># 定义空白图像，用于输出中值滤波后的结果</span><br>    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(num, h - num):  <span class="hljs-comment"># 遍历出原图像</span><br>        <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(num, w - num):<br>            <span class="hljs-built_in">sum</span> = []; sum1 = []<br>            <span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(i - num, i + num + <span class="hljs-number">1</span>):  <span class="hljs-comment"># 求中心像素周围size*size区域内的像素的平均值</span><br>                <span class="hljs-keyword">for</span> l <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(j - num, j + num + <span class="hljs-number">1</span>):<br>                    <span class="hljs-built_in">sum</span> = <span class="hljs-built_in">sum</span> + [<span class="hljs-built_in">int</span>(img[k, l][<span class="hljs-number">0</span>]) + <span class="hljs-built_in">int</span>(img[k, l][<span class="hljs-number">1</span>]) + <span class="hljs-built_in">int</span>(img[k, l][<span class="hljs-number">2</span>])]  <span class="hljs-comment"># 每个像素的3通道像素值相加，然后求中间数</span><br>                    sum1 = sum1 + [(img[k, l][<span class="hljs-number">0</span>], img[k, l][<span class="hljs-number">1</span>], img[k, l][<span class="hljs-number">2</span>])]  <span class="hljs-comment"># 将对于的三通道像素值存在数组sum1中</span><br>            <span class="hljs-built_in">id</span> = np.argsort(<span class="hljs-built_in">sum</span>)  <span class="hljs-comment"># 将像素值周围的点的数组进行排序，然后返回排序之前的像素值对应在数组中的序号</span><br>            <span class="hljs-built_in">id</span> = <span class="hljs-built_in">id</span>[<span class="hljs-built_in">int</span>((size ** <span class="hljs-number">2</span>) / <span class="hljs-number">2</span>) + <span class="hljs-number">1</span>]  <span class="hljs-comment"># 取返回序号的中间序号</span><br>            img1[i, j] = sum1[<span class="hljs-built_in">id</span>]  <span class="hljs-comment"># 通过中间序号找到在像素值数组中的3通道信号</span><br>    <span class="hljs-keyword">return</span> img1<br></code></pre></td></tr></table></figure>

<h1 id="2-4运行测试"><a href="#2-4运行测试" class="headerlink" title="2.4运行测试"></a>2.4运行测试</h1><p><strong>原图：</strong><br><img src="https://imgbed.cheney.cc/picgo/16f32cde5ef0441d8689e23b83eb9d46-20220405210303491.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>噪声</strong><br><img src="https://imgbed.cheney.cc/picgo/83ff5a02ffae4f97b49494b61ef2c08d-20220405210303535.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>加噪后的图片：</strong><br><img src="https://imgbed.cheney.cc/picgo/0c759ed1a1bb42679c7234dfe6864688-20220405210303610.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>去噪后的图片：</strong><br><img src="https://imgbed.cheney.cc/picgo/4ca2c85f8c6c4b5fbab770601a31b441-20220405210303664.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>总体对比图：</strong><br><img src="https://imgbed.cheney.cc/picgo/fc24a10fdbeb44e1bf48391a0ab997f1-20220405210303750.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>程序计算出的误差与相似度：</strong><br><img src="https://imgbed.cheney.cc/picgo/e134fa3bd95949eeadfcd016db009a3f-20220405210303799.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>即：<br>恢复图片与原始图片的评估误差:5140.961<br>恢复图片与原始图片的SSIM 相似度:0. 12262643111991207<br>恢复图片与原始图片的Cosine 相似度:0.8794560914526841</p>
<p>通过上述误差的分析和人眼对修复后的图片的观察可知程序在一定程度上修复了含有噪声的图片，但修复效果仍有一定的提升空间。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/">人工智能</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Python/">Python</a>
                    
                      <a class="hover-with-bg" href="/tags/OpenCv/">OpenCv</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/10/04/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD__GAN%E6%89%8B%E5%86%99%E4%BD%93%E7%94%9F%E6%88%90(MINIST)/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">GAN手写体生成(MINIST)</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/10/02/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD__%E8%8A%B1%E5%8D%89%E8%AF%86%E5%88%AB(tensorflow)/">
                        <span class="hidden-mobile">花卉识别(tensorflow)</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://cheney822.gitee.io/" target="_blank" rel="nofollow noopener"><span>备用网址</span></a> 
  </div>
  

  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        皖ICP备2022002876号-1
      </a>
    </span>
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
